package J0120;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class Solution3 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode tmp = null;
        while(cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tree = stack.peek();
            cur = tree.right;
            if(cur == tmp || cur == null) {
                tmp = stack.pop();
                list.add(tmp.val);
                cur = null;
            }
        }
        return list;
    }
}
